//
//  SuperViewController.m
//  MissAndFound
//
//  Created by apple on 14-12-4.
//  Copyright (c) 2014年 apple. All rights reserved.
//

#import "SuperViewController.h"
#import "FZYLoginVC.h"
#import "FZYBankAccountController.h"
#import <IQKeyboardManager/IQKeyboardManager.h>

@interface SuperViewController ()<UIAlertViewDelegate,UITextViewDelegate,RDVTabBarControllerDelegate,FZYPublicAlertViewDelegate>

@property(nonatomic,strong)UIControl *big;
@property(nonatomic,strong)UIDatePicker *TimePickerView;
@property(nonatomic,strong)UIPickerView *pickView;
@property(nonatomic,strong)NSMutableArray *timeArr,*shiArr,*quArr;
@property(nonatomic,strong)UIImageView *SelectImg;
@property(nonatomic,strong)NSArray *addressArr;
@property(nonatomic,assign)BOOL isround;
@property(nonatomic,assign)int present;
@property(nonatomic,strong)MBProgressHUD *HUD,*HUDString;


@property (nonatomic, strong)UIButton * phoneBtn;//语音验证码弹窗


@end
@implementation SuperViewController
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if([self isKindOfClass:[FZYLoginVC class]] || [self isKindOfClass:[FZYGlobalHtmlVC class]]){
       
        self.floatView.hidden = YES;
    }else{
        self.floatView.hidden = NO;
    }
}
-(void)goModifyBankAccountVC{
    FZYBankAccountController *vc = FZYBankAccountController.new;
    [self.navigationController pushViewController:vc animated:YES];
}
-(NSInteger)startTime{
    if(_startTime==0){
        _startTime = (NSInteger)[[NSDate new] timeIntervalSince1970] * 1000;
    }
    return _startTime;
}
-(NSInteger)endTime{
    return  (NSInteger) [[NSDate new] timeIntervalSince1970] * 1000;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.infoDict = @{};
    // Do any additional setup after loading the view.
    self.dataDict = [NSMutableDictionary new];
    self.dataArray = [NSMutableArray new];
    self.index = 1;
    _appdelegate=(AppDelegate *)[UIApplication sharedApplication].delegate;
    @weakify(self)
    [[NSNotificationCenter defaultCenter]addObserverForName:@"AlertDismiss" object:nil queue:nil usingBlock:^(NSNotification * _Nonnull notification) {
        @strongify(self);
        delayOperation(0.1, ^{
            
            [_feedbackAlertV removeFromSuperview];
            _feedbackAlertV = nil;
        });
            
    }];
   
    
    self.navigationController.interactivePopGestureRecognizer.delegate = (id)self;

    if ([self respondsToSelector:@selector(setEdgesForExtendedLayout:)])
    {
        [self setEdgesForExtendedLayout:UIRectEdgeNone];
    }
    self.fd_interactivePopDisabled = NO;
    self.navigationController.fd_fullscreenPopGestureRecognizer.enabled = YES;
    self.fd_prefersNavigationBarHidden=YES;
    
    _scale=1.0;
    if ([[UIScreen mainScreen] bounds].size.height > 480){
        if (kStatusBar_Height() > 20){
            _scale= 667.0/568.0;
        }
        else{
            _scale = [[UIScreen mainScreen] bounds].size.height / 568.0;
        }
    }
    if([self isKindOfClass:[FZYLoginVC class]]){
        
    }else{
        delayOperation(1, ^{
            [JF_KEY_WINDOW() addSubview:self.floatView];
        });
    }

    [self preferredStatusBarStyle];
    IQKeyboardManager *manager = [IQKeyboardManager sharedManager];
    manager.enable = YES;
    manager.shouldResignOnTouchOutside = YES;
    manager.shouldToolbarUsesTextFieldTintColor = YES;
    manager.enableAutoToolbar = YES;
    manager.shouldPlayInputClicks = YES;
    manager.shouldShowToolbarPlaceholder = YES;
    
//    [IQKeyboardManager sharedManager].enable=YES;
//    [IQKeyboardManager sharedManager].enableAutoToolbar=YES;
//    [IQKeyboardManager sharedManager].shouldResignOnTouchOutside = YES;
   self.navigationController.navigationBarHidden=YES;
    self.view.backgroundColor = Hex_Str_COLOR(@"#F7F7F5");

   
    self.NavImg = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0,self.view.width,NAVIGATION_BAR_HEIGHT())];
    self.NavImg.backgroundColor=[UIColor whiteColor];
    self.NavImg.userInteractionEnabled = YES;
    self.NavImg.clipsToBounds = YES;
    [self.view  addSubview:self.NavImg];
    
    [self.NavImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.mas_equalTo(self.view);
        make.height.mas_equalTo(NAVIGATION_BAR_HEIGHT());
    }];
    
    _Navline = [[UIImageView alloc]initWithFrame:CGRectMake(0, self.NavImg.bottom-.5, self.view.width, .5)];
    _Navline.backgroundColor=mainSepartorColor();

    self.TitleLabel = [[UILabel alloc] initWithFrame:CGRectMake(45*self.scale,kStatusBar_Height(), self.view.width-90*self.scale, 44)];
    self.TitleLabel.textColor = Text_COLOR_LEVEL1();
    self.TitleLabel.textAlignment = 1;
    self.TitleLabel.font = fontWithWeight(16, UIFontWeightMedium);
    self.TitleLabel.backgroundColor = [UIColor clearColor];
    [self.NavImg addSubview:self.TitleLabel];
    
    _backBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, self.TitleLabel.top, self.TitleLabel.height, self.TitleLabel.height)];
    [_backBtn addTarget:self action:@selector(PopVC:) forControlEvents:(UIControlEventTouchUpInside)];
    [self.NavImg addSubview:_backBtn];
    
    
    _rightBarBtn = [[UIButton alloc]initWithFrame:(CGRectMake(kAppW()-60,_backBtn.top, self.TitleLabel.height, self.TitleLabel.height))];
    [self.NavImg addSubview:_rightBarBtn];
    [self defaultNaviConfig];

    delayOperation(0.1, ^{
        if(JMProjectManager.sharedJMProjectManager.loginUser.servicePhone.length==0 &&JMProjectManager.sharedJMProjectManager.loginUser.token.length !=0){
            [[JMBaseRequest sharedInstance]requestBasePost:BasePostRequestUrl(@"/api/common/customerServiceInfo") params:nil success:^(NSDictionary * _Nullable dataDic, NSArray * _Nullable dataArray) {
                JMProjectManager.sharedJMProjectManager.loginUser.servicePhone = [dataDic safeStringForKey:@"phone"];
                [self.phoneBtn setTitle:[dataDic safeStringForKey:@"phone"] forState:(UIControlStateNormal)];
                [self.phoneBtn TiaoZhengButtonWithOffsit:5 TextImageSite:(UIButtonTextLeft)];
            } fail:^(NSString * _Nonnull errorMsg) {
                
            }];
        }else{
            [_phoneBtn setTitle:JMProjectManager.sharedJMProjectManager.loginUser.servicePhone forState:(UIControlStateNormal)];
            [self.phoneBtn TiaoZhengButtonWithOffsit:5 TextImageSite:(UIButtonTextLeft)];

        }
    });
}

-(void)popToVC:(NSString *)className{
    // 替换成你的目标控制器类名
    Class targetClass = NSClassFromString(className);
    if (targetClass) {
        for (UIViewController *viewController in self.navigationController.viewControllers) {
            if ([viewController isKindOfClass:targetClass]) {
                [self.navigationController popToViewController:viewController animated:YES];
                break;
            }
        }
    }
}
-(void)showMessage:(NSString *)message{
    delayOperation(0, ^{
        if ([[NSString stringWithFormat:@"%@",message] isEmptyString]) {
            return;
        }
        self.HUDString = [MBProgressHUD showHUDAddedTo:JF_KEY_WINDOW() animated:YES];
        self.HUDString.contentColor = WhiteColor();
        self.HUDString.bezelView.blurEffectStyle = UIBlurEffectStyleDark;
        self.HUDString.label.textColor = WhiteColor();
        self.HUDString.mode = MBProgressHUDModeText;
        self.HUDString.detailsLabel.text= message;
        self.HUDString.label.font= Font(12);
        self.HUDString.removeFromSuperViewOnHide = YES;
        [self.HUDString hideAnimated:YES afterDelay:1.5];

    });
}
-(void)showSuccess:(NSString *)message{
    if ([[NSString stringWithFormat:@"%@",message] isEmptyString]) {
        return;
    }
    delayOperation(0, ^{
        UIImageView *checkmarkImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"auth_success"]]; // 替换为你的成功对勾图片
        self.HUDString = [MBProgressHUD showHUDAddedTo:JF_KEY_WINDOW() animated:YES];
        self.HUDString.customView = checkmarkImageView;
        self.HUDString.mode = MBProgressHUDModeCustomView;
        self.HUDString.contentColor = WhiteColor();
        self.HUDString.bezelView.blurEffectStyle = UIBlurEffectStyleDark;
        self.HUDString.label.textColor = WhiteColor();
        self.HUDString.label.text= message;
        self.HUDString.label.font= Font(14);
        self.HUDString.removeFromSuperViewOnHide = YES;
        [self.HUDString hideAnimated:YES afterDelay:1.5];
    });
    
}
//  MARK: -  ————导航条————
- (void)defaultNaviConfig {
    [self.backBtn setImage:ImageNamed(@"login_back") forState:(UIControlStateNormal)];
}
- (void)setRightBarBtnWithImage:(NSString *)imgName Target:(id)target Action:(SEL)action {
    [self.rightBarBtn setImage:ImageNamed(imgName) forState:(UIControlStateNormal)];
    [self.rightBarBtn addTarget:target action:action forControlEvents:(UIControlEventTouchUpInside)];
}
- (void)setRightBarBtnWithTitle:(NSString *)title TitleColor:(UIColor *)color Target:(id)target Action:(SEL)action {
    [self.rightBarBtn setTitle:title forState:(UIControlStateNormal)];
    [self.rightBarBtn setTitleColor:color forState:(UIControlStateNormal)];
    [self.rightBarBtn addTarget:target action:action forControlEvents:(UIControlEventTouchUpInside)];
}

-(void)PopVC:(UIButton *)sender{
    
    [self backBtnClick];
}
-(void)backBtnClick{
    if ([self isKindOfClass:[FZYGlobalHtmlVC class]] || [self isKindOfClass:[JMWebViewController class]]) {
//        if (self.navigationController.viewControllers.count==0) {
//
//        }
        [self dismissModalViewControllerAnimated:YES];
    }
    [self.navigationController popViewControllerAnimated:YES];

}

#pragma mark-----请求服务器  开始和结束的动画

-(void)startAnimating:(NSString *)set{
    
    delayOperation(0, ^{
        if (self.HUD) {
            [self.HUD removeFromSuperview];
            self.HUD=nil;
        }
        self.HUD = [MBProgressHUD showHUDAddedTo:JF_KEY_WINDOW() animated:YES];
        self.HUD.contentColor = WhiteColor();
        self.HUD.bezelView.blurEffectStyle = UIBlurEffectStyleDark;
        self.HUD.label.textColor = WhiteColor();
        self.HUD.mode = MBProgressHUDModeIndeterminate;
        if ([[NSString stringWithFormat:@"%@",set] isEmptyString]) {
            self.HUD.label.text = @"loading...";
        }
        self.HUD.label.text = set;
        self.HUD.removeFromSuperViewOnHide = NO;
        [self.HUD hideAnimated:YES afterDelay:20];

    });
}


-(void)stopAnimating{
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.HUD removeFromSuperview];
        [self.HUD hideAnimated:YES];
        self.HUD = nil;
    });
   
}

#pragma mark--------图片按比例压缩，
-(UIImage *) scaleImage: (UIImage *)image scaleFactor:(float)scaleBy
{
    if (image.size.width>1000) {
        scaleBy = 1000/image.size.width;
    }else{
        scaleBy= 1.0;
    }
    CGSize size = CGSizeMake(image.size.width * scaleBy, image.size.height * scaleBy);
    UIGraphicsBeginImageContext(size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGAffineTransform transform = CGAffineTransformIdentity;
    transform = CGAffineTransformScale(transform, scaleBy, scaleBy);
    CGContextConcatCTM(context, transform);
    [image drawAtPoint:CGPointMake(0.0f, 0.0f)];
    UIImage *newimg = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newimg;
}

// 生成随机boundary字符串的函数
- (NSString *)generateBoundaryString {
    JMAppConfig *config = JMProjectManager.sharedJMProjectManager.appConfig;
    return [NSString stringWithFormat:@"Boundary-%@", config.uuidString];
}
-(void)openCreditUrl:(NSString *)type{
    //1fico 2cloundun 3faq
//    [self startAnimating:nil];
    JMLoginUserModel *user = JMProjectManager.sharedJMProjectManager.loginUser;
    NSString *creditUrl;
    NSString *title;
    if (type.intValue==1) {
        creditUrl =[NSString stringWithFormat:@"%@/app-loanmarket-h5-creditreport/#/fico?phone=%@&userId=%@",serviceUrl(),user.phone,user.userId];
        title = @"My FICO";
        [JMCommonMethod uploadStatistics:@"CreditReport" actionType:@"Enter" parameters:nil];
    }
    if (type.intValue==2) {
        creditUrl =[NSString stringWithFormat:@"%@/app-loanmarket-h5-creditreport/#/cloudun?phone=%@&userId=%@",serviceUrl(),user.phone,user.userId];
        title = @"My Cloundun";
        [JMCommonMethod uploadStatistics:@"CreditReport" actionType:@"Enter" parameters:nil];
    }
    if ([type isEqualToString:@"3"]) {
        creditUrl = [NSString stringWithFormat:@"%@/app-loanmarket-h5-faq/#/FAQ?token=%@&packageName=%@",serviceUrl(),user.token,bundleId];
        [JMCommonMethod uploadStatistics:@"FAQ" actionType:@"Enter" parameters:nil];

    }
    FZYGlobalHtmlVC *vc = FZYGlobalHtmlVC.new;
    vc.url = creditUrl;
    vc.titleString = @"";
    [self.navigationController pushViewController:vc animated:YES];

   
}
-(void)presentWebviewWithUrl:(NSString *)urlString andTitle:(NSString *)title{
    FZYGlobalHtmlVC *vc = FZYGlobalHtmlVC.new;
    vc.url = urlString;
    vc.titleString = title;
    if([urlString containsString:loginLoanAgreement]){
        [JMCommonMethod uploadStatistics:@"Agreement" actionType:@"Enter" parameters:@{@"type":@"Loan"}];
    }
    if([urlString containsString:loginPrivacyAgreement]){
        [JMCommonMethod uploadStatistics:@"Agreement" actionType:@"Enter" parameters:@{@"type":@"Privacy"}];
    }
    if([urlString containsString:LoginRegistrationAgreement]){
        [JMCommonMethod uploadStatistics:@"Agreement" actionType:@"Enter" parameters:@{@"type":@"Register"}];
    }
    if([urlString containsString:@"credit-report"]){
        [JMCommonMethod uploadStatistics:@"CreditReport" actionType:@"Enter" parameters:nil];
    }
    [self.navigationController pushViewController:vc animated:YES];

}
-(FZYFloatIcon *)floatView{
    
    if(!_floatView){
        _floatView = [FZYFloatIcon sharedFZYFloatIcon];
        _floatView.frame = CGRectMake(kAppW() - 86, self.view.height - 86 -TAB_BAR_HEIGHT(), 48, 48);
        _floatView.userInteractionEnabled = YES;
        [_floatView setImage:ImageNamed(@"service")];
        @weakify(self)
        [_floatView tapAction:^(UIView *sender) {
            @strongify(self);
            [self.feedbackAlertV show];
        }];
    }
    return _floatView;
}

-(void)commitFeedBack{
    if(self.textV.textView.text.length==0){
        return;
    }
    NSDictionary *para = @{
        @"title" : self.TitleLabel.text?:@"",
        @"content": @{@"info":self.infoDict,@"content":self.textV.textView.text}.jsonStringEncoded
    };
    // [self startAnimating:nil];

    @weakify(self)
    [[JMBaseRequest sharedInstance] requestBasePost:BasePostRequestUrl(@"/api/user/complaint") params:para success:^(NSDictionary * _Nullable dataDic, NSArray * _Nullable dataArray) {
        @strongify(self)
        dispatch_async(dispatch_get_main_queue(), ^{
            [self stopAnimating];
            [self.feedbackAlertV.firstBtn endLoading];
            [self.feedbackAlertV dismiss];
            [self showSuccess:@"Enviado con éxito"];
            [self.navigationController popToRootViewControllerAnimated:YES];
        });
        } fail:^(NSString * _Nonnull errorMsg) {
            [self stopAnimating];
        }];
}
- (void)textFieldDidChangeValue:(NSNotification *)notification
{
    UITextView *sender = (UITextField *)[notification object];
    if (sender.text.length) {
        _feedbackAlertV.firstBtn.enable = YES;
    }else{
        _feedbackAlertV.firstBtn.enable = NO;
    }
}
///api/user/complaint
-(FZYPublicAlertView *)feedbackAlertV{
    if(!_feedbackAlertV){
        @weakify(self)
        _feedbackAlertV =  [FZYPublicAlertView showAlertWithFrame:(CGRectMake(0, 0, kAppW()-36, 190+376))
                                         Title:@"Comentarios"
                                      subTitle:@"Por favor, anote cualquier realimentacion que pueda tener" BottomBtns:@[@"Subir"]
                                      Position:FZYPublicAlertViewPositionCenter btnDirection:FZYPublicAlertViewButtonDirectionVer btnActionBlock:^(NSInteger btnTag) {
            @strongify(self);
            [self commitFeedBack];
            
        }];
        [_feedbackAlertV.topImgV setImage:ImageNamed(@"feedback_top")];
        _feedbackAlertV.topImgV.height = 190;
        _feedbackAlertV.topImgV.top = -22;
        
        _feedbackAlertV.firstBtn.enable = NO;

        
        
        _feedbackAlertV.firstBtn.bottom = _feedbackAlertV.height-166;
        _textV = [[BRPlaceholderTextView alloc]initWithFrame:(CGRectMake(20, _feedbackAlertV.firstBtn.top-170, _feedbackAlertV.width-40, 150))];
        [_feedbackAlertV addSubview:_textV];
        _textV.backgroundColor = Hex_Str_COLOR(@"#F4F4F4");
        _textV.cornerRadius =10;
        _textV.placeholder = @"Por favor escribe";
        _textV.maxTextLength = 200;
        
        
        [_textV addTextViewChangeEvent:^(BRPlaceholderTextView *text) {
            @strongify(self);

            if (text.textView.text.length) {
                self.feedbackAlertV.firstBtn.enable = YES;
            }else{
                self.feedbackAlertV.firstBtn.enable = NO;
            }
        }];
//        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldDidChangeValue:) name:UITextFieldTextDidChangeNotification object:self.textV.textView];

        UILabel *tipsLab = [FZYControl createLabelWithFrame:(CGRectMake(20, _feedbackAlertV.firstBtn.bottom+20, _feedbackAlertV.firstBtn.width, 60)) Font:Font(14) Text:@"También puede ponerse en contacto directamente con el servicio de atención al cliente" color:Text_COLOR_LEVEL1()];
        [_feedbackAlertV addSubview:tipsLab];
        
        _phoneBtn = [FZYControl createButtonWithFrame:(CGRectMake(tipsLab.left, tipsLab.bottom+5, tipsLab.width, 46)) ImageName:@"copy" Target:self Action:@selector(copyBtnClick) font:Font(16) Title:JMProjectManager.sharedJMProjectManager.loginUser.servicePhone];

        
        [_feedbackAlertV addSubview:_phoneBtn];
        _phoneBtn.backgroundColor = Hex_Str_COLOR(@"#FBFED4");
        _phoneBtn.cornerRadius = 12;
        [_phoneBtn setTitle:JMProjectManager.sharedJMProjectManager.loginUser.servicePhone forState:(UIControlStateNormal)];
        [_phoneBtn TiaoZhengButtonWithOffsit:5 TextImageSite:(UIButtonTextLeft)];
        
    }
    return _feedbackAlertV;
}

-(void)copyBtnClick{
    UIPasteboard *past = [UIPasteboard generalPasteboard];
    past.string = JMProjectManager.sharedJMProjectManager.loginUser.servicePhone;
    NSLog(@"%@",JMProjectManager.sharedJMProjectManager.loginUser.servicePhone);
    [self showSuccess:@"Copia exitosa"];
}


-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
#pragma clang diagnostic pop
@end
